#include <Arduino.h>
#include "xx_tool.h"

const char *device_name = "RADAR";
// 协议
const char *topic_distance = "D"; // 测距
const char *topic_servo = "S";    // 舵机控制

const char *topic_light = "L"; // 灯

void xx_mqtt_onMessageReceived(const char *topic, const char *payload)
{
  Serial.println(topic);
  if (String(topic) == String(topic_distance))
  {
    String topic_distance_a = String(topic_distance) + "_A";
    String distance_str = String(xx_distance());
    xx_mqtt_sendMessage(topic_distance_a.c_str(), distance_str.c_str());
  }
  else if (String(topic) == String(topic_servo))
  {
    int angle = String(payload).toInt(); // 将payload转换为整数
    if (angle >= 0 && angle <= 180)
    { // 检查角度是否在有效范围内
      xx_servoSetAngle(angle);
    }
    else
    {
      Serial.println("Invalid angle value received.");
    }
  }
  else if (String(topic) == String(topic_light))
  {
    String type = String(payload);
    Serial.println(type);
    if (type == String("off"))
    {
      xx_let_setLightMode(PINK);
      /* code */
    }else if (type == String("on"))
    {
      xx_let_setLightMode(RAINBOW_FLOW);
    }else{
      Serial.println("no topic match led");
    }
    
  }
  else
  {
    Serial.println("no topic match");
  }
}
void setup()
{

  xx_tool_setup();
  xx_distance_setup();
  xx_servo_setup();

  xx_led_setup();

  vector<const char *> topics;
  topics.push_back(topic_distance);
  topics.push_back(topic_servo);
  topics.push_back(topic_light);
  xx_mqtt_setup(device_name, topics);
  xx_mqtt_setOnMessageReceived(xx_mqtt_onMessageReceived);
}

void loop()
{
  xx_mqtt_loop();
}
